package com.ltx.blog_ltx.server;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class tasksService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Scheduled(cron = "0 0 0 * * ?")
    public void Heats(){
        List redu = redisTemplate.opsForList().range("heats", 0, -1);
        Map<String, Long> nameMap = (Map<String, Long>) redu.stream().collect(Collectors.groupingBy(p -> p, Collectors.counting()));  //把所有的id出现次数统计出来
        for(int j=0;j<3;j++){
            Long Max=0l;
            String MaxString="";
            for (String s : nameMap.keySet()) {
                Long aLong = nameMap.get(s);
                if(aLong>Max){
                    Max=aLong;
                    MaxString=s;
                }
            }
            redisTemplate.opsForList().rightPush("heatTop3",Integer.parseInt(MaxString));
            nameMap.remove(MaxString,Max);    //移除最大的value对应的元素，找下一个最大的。
        }
        //把heats的所有元素都弹出
        int x= Math.toIntExact(redisTemplate.opsForList().size("heats"));
        for (int i=0;i<x;i++){
            redisTemplate.opsForList().leftPop("heats");
        }
    }

}
